<template>
    <button class="button" :style="{
        width: props.block && '100%',
        cursor: props.disabled && 'default'
    }" :disabled="props.disabled" @click="$emit('button-click')" @mouseenter="onMouseenter" @mouseleave="onMouseleave">
        <span ref="textSpan">{{ props.children }}</span>
        <span ref="circleSpan"></span>
        <span ref="bgSpan"></span>
    </button>
</template>

<script setup>
import { gsap } from 'gsap';
import { onMounted, shallowRef, ref } from 'vue';

const props = defineProps({
    children: {
        type: String,
        default: "Order Now"
    },
    block: {
        type: Boolean,
        default: false
    },
    disabled: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['button-click'])

// 使用ref引用具体的DOM元素
const textSpan = ref(null)
const circleSpan = ref(null)
const bgSpan = ref(null)

const tl = shallowRef(null)

onMounted(() => {
    tl.value = gsap.timeline({
        defaults: {
            ease: 'power4.in'
        },
        paused: true
    })
    
    // 使用ref引用的元素而不是全局选择器
    tl.value.to(textSpan.value, {
        x: 10,
        duration: 0.2
    }).to(circleSpan.value, {
        scale: 1
    }, ">").to(bgSpan.value, {
        x: 0
    })
})

const onMouseenter = () => {
    if (!props.disabled && tl.value) tl.value.play()
}

const onMouseleave = () => {
    if (tl.value) tl.value.reverse()
}
</script>
<style scoped>
.button {
    height: 40px;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    text-align: center;
    text-decoration: none;
    z-index: 2;
    color: #fafafa;
    background-color: #ff4520;
    border: none;
    padding: 0 25px;
    font-size: 18px;
    border-radius: 50px;
    font-weight: bold;
    line-height: 40px;

    span:nth-of-type(1) {
        display: inline-block;
    }

    span:nth-of-type(2) {
        background-color: #fafafa;
        border-radius: 50%;
        height: 14px;
        width: 14px;
        position: absolute;
        left: 13px;
        top: 13px;
        z-index: -1;
        transform: scale(0);
    }

    span:nth-of-type(3) {
        border-radius: inherit;
        inset: 0;
        position: absolute;
        z-index: -2;
        background-color: #ff6b00;
        transform: translateX(-100%);
    }
}
 
.button:hover {
    background-color: #000;
    color: #fff;
}
</style>